﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using SusuCMS.Caching;

namespace SusuCMS.Web
{
    public class CmsControllerBase : Controller
    {
        protected override void Initialize(RequestContext requestContext)
        {
            var host = requestContext.HttpContext.Request.Headers["host"];
            var url = requestContext.RouteData.Values["url"] as string;
            var pageContext = new PageContext { Host = host };

            // home page
            if (string.IsNullOrWhiteSpace(url))
            {
                if (CmsDataCache.OnlineHosts.ContainsKey(host))
                {
                    var websiteId = CmsDataCache.OnlineHosts[host];
                    pageContext.CurrentWebsite = CmsDataCache.OnlineWebsites[websiteId];
                    pageContext.CurrentPage = CmsDataCache.OnlineHomePages[websiteId];
                }
            }
            else
            {
                url = url.ToLower();
                var splitted = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                var subDirectory = splitted[0].ToLower();
                var hostWithPath = host + "/" + subDirectory;
                if (CmsDataCache.OnlineHosts.ContainsKey(hostWithPath))
                {
                    pageContext.SubDirectory = subDirectory;

                    var websiteId = CmsDataCache.OnlineHosts[hostWithPath];
                    pageContext.CurrentWebsite = CmsDataCache.OnlineWebsites[websiteId];
                    var newUrl = url.Replace(subDirectory, "").TrimStart(new[] { '/' });
                    if (string.IsNullOrWhiteSpace(newUrl))
                    {
                        pageContext.CurrentPage = CmsDataCache.OnlineHomePages[websiteId];
                    }
                    else
                    {
                        pageContext.CurrentPage = CmsApplication.GetPageRepository(UnitOfWork).FindAll()
                            .Where(i => i.WebsiteId == websiteId && i.IsPublished == true)
                            .FirstOrDefault(i => i.Url.Equals(newUrl, StringComparison.OrdinalIgnoreCase));
                    }
                }
                else
                {
                    if (CmsDataCache.OnlineHosts.ContainsKey(host))
                    {
                        var websiteId = CmsDataCache.OnlineHosts[host];
                        pageContext.CurrentWebsite = CmsDataCache.OnlineWebsites[websiteId];
                        pageContext.CurrentPage = CmsApplication.GetPageRepository(UnitOfWork).FindAll()
                            .Where(i => i.WebsiteId == websiteId && i.IsPublished == true)
                            .FirstOrDefault(i => i.Url.Equals(url, StringComparison.OrdinalIgnoreCase));
                    }
                }
            }

            CmsApplication.SetPageContext(pageContext);

            base.Initialize(requestContext);
        }

        protected IUnitOfWork UnitOfWork
        {
            get
            {
                if (this._UnitOfWork == null)
                {
                    this._UnitOfWork = CmsApplication.GetDataContext();
                }

                return this._UnitOfWork;
            }
        }
        private IUnitOfWork _UnitOfWork;

        protected PageContext PageContext
        {
            get
            {
                if (_PageContext == null)
                {
                    _PageContext = CmsApplication.GePageContext();
                }

                return _PageContext;
            }
        }
        private PageContext _PageContext;

        protected new ActionResult HttpNotFound()
        {
            var website = PageContext.CurrentWebsite;
            if (website != null)
            {
                var fileName = string.Format("~/wwwroot/{0}/Views/Shared/NotFound.cshtml", website.Identifier);
                if (System.IO.File.Exists(Server.MapPath(fileName)))
                {
                    return View(fileName);
                }
            }

            return View("~/Views/Shared/NotFound.cshtml");
        }

    }
}
